package com.wpzf.ndhc.utils;


import com.wpzf.ndhc.domain.CheckDTO;
import com.wpzf.zxhc.utils.OBSUploadUnits;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.xssf.usermodel.*;
import org.junit.Test;

import java.io.*;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

public class CheckUtil {


    //DB检查方法 nacos
    public Map<String, Object> chedktool(String exePath, String dbPath, String dbPass) {
        Map<String, Object> rest = new HashMap<>();
        try {
//          exePath="D:\\wpzf\\LandCloud.CGDBPreCheckTool\\LandCloud.CGDBPreCheckTool.exe";
            //dbPath="D:\\1111\\清河区举证数据包.db";
            //dbPass="ka78RExgIlrM3YJ2JhSjVbHjJTNG";
            //exePath="D:\\LandCloudCGDBPreCheckTool\\LandCloud.CGDBPreCheckTool\\LandCloud.CGDBPreCheckTool.exe";
            //dbPath="D:\\LandCloudCGDBPreCheckTool\\WPZFNDTB2024参考_123456.db";
            //dbPass="123456";

            // 要执行的cmd命令
            String command = String.format("%s  checkdb --file=%s --pwd=%s", exePath, dbPath, dbPass);
            // 执行命令
            Process process = Runtime.getRuntime().exec(command);
            // 读取命令执行结果
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), Charset.forName("GBK")));
            String line;
            StringBuilder output = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                output.append(line).append("\n");
            }
            // 等待命令执行完成
            process.waitFor();
            if (output.toString().contains("签章成功，请查看签章文件")) {
                rest.put("code", 200);
                rest.put("signpath", dbPath.replace(".db", ".sign"));
                rest.put("logpath",dbPath.replace(".db", ".log"));
                rest.put("message", "成果包校验结束，校验结果：通过");
                return rest;
            } else {
                System.out.println("校验未通过！");
                rest.put("code", 500);
                rest.put("logpath",dbPath.replace(".db", ".log"));
                rest.put("message", "校验未通过," + output.toString());
                return rest;
            }

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("校验未通过！");
            rest.put("code", 500);
            rest.put("message", "校验未通过," + e.toString());
            return rest;
        }
    }
    public Map<String, Object> chedklog(String logPath, String xzqdm) throws IOException
    {
        Map<String, Object> rest=new HashMap<>();
        List<CheckDTO> checkDTOS=new ArrayList<>();
        //解析日志文件 并解析存储到表
        try (BufferedReader br = new BufferedReader(new FileReader(logPath)))
        {
            String line;
            while ((line = br.readLine()) != null)
            {
                // 去掉首尾的方括号，并去掉部分之间的空格和方括号
                String trimmedInput = line.trim().substring(1, line.length() - 1);
                String[] parts = trimmedInput.split("\\] \\[");
                if(parts!=null)
                {
                    if (parts.length > 0&&parts.length==6)
                    {
                        if(parts[1].toString().equals("error") || parts[1].toString().equals("info"))
                        {
                            CheckDTO checkDTO=new CheckDTO();
                            checkDTO.setTime(parts[0].toString().replace("[",""));
                            checkDTO.setInfoLevel(parts[1].toString());
                            checkDTO.setTablename(parts[2].toString());
                            checkDTO.setId(parts[3].toString().replace("id:",""));
                            checkDTO.setMessage(parts[4].toString().replace("message:",""));
                            checkDTOS.add(checkDTO);
                        }
                    }
                    else  if (parts.length > 0&&parts.length==4)
                    {
                        if(parts[1].toString().equals("error") || parts[1].toString().equals("info"))
                        {
                            CheckDTO checkDTO=new CheckDTO();
                            checkDTO.setTime(parts[0].toString().replace("[",""));
                            checkDTO.setInfoLevel(parts[1].toString());
                            checkDTO.setMessage(parts[3].toString().replace("message:",""));
                            checkDTOS.add(checkDTO);
                        }
                    }
                }
            }
            List<String> Colomnlist=new ArrayList<>();
            Colomnlist.clear();
            Colomnlist.add("表名");
            Colomnlist.add("级别");
            Colomnlist.add("定位字段");
            Colomnlist.add("定位值");
            Colomnlist.add("检查字段值");
            Colomnlist.add("错误描述");
            Colomnlist.add("包名");
            XSSFWorkbook workbook = new XSSFWorkbook();
            XSSFSheet sheet01 = workbook.createSheet("sheet1");
            XSSFRow row = sheet01.createRow(0);
            XSSFCellStyle style = workbook.createCellStyle();
            style.setAlignment(HorizontalAlignment.CENTER);
            int i = 0;
            for (String item : Colomnlist) {
                XSSFCell cell = row.createCell(i);
                String colName = (item);
                cell.setCellValue(colName);
                i++;
            }
            String nowDate = new SimpleDateFormat("yyyyMMddHHMMss").format(new Date());
            //checkDTOS 错误信息 与数据库对照
            if(checkDTOS.size()>0)
            {
                //图斑表错误信息
                for(int k=0;k<checkDTOS.size();k++)
                {
                    CheckDTO checkDTO=checkDTOS.get(k);
                    row = sheet01.createRow(k + 1);
                    row.createCell(0).setCellValue(checkDTO.getTablename()+"");
                    row.createCell(1).setCellValue(checkDTO.getInfoLevel()+"");
                    row.createCell(2).setCellValue("BSM");
                    row.createCell(3).setCellValue(checkDTO.getId());
                    row.createCell(4).setCellValue("(xzqdm,bsm) = ("+xzqdm+","+checkDTO.getId()+")");
                    row.createCell(5).setCellValue(checkDTO.getMessage()+"");
                    row.createCell(6).setCellValue(xzqdm+nowDate);
                }
                rest.put("info", "DB包质检未通过");
            }
            else
            {
                rest.put("info", "DB包质检通过");
            }
            String tempath=System.getProperty("user.dir") + "\\" + "dbFile";
            String filepath=tempath + "/" + xzqdm+nowDate + ".xlsx";
            FileOutputStream fileOut = new FileOutputStream(filepath);
            workbook.write(fileOut);
            fileOut.close();

            String OBSAddress = "saveResult" + "/log/" + xzqdm+nowDate + ".xlsx";
            AtomicInteger attemptCount = new AtomicInteger(0);
            String log;
            do {
                log = OBSUploadUnits.OBSUpload(OBSAddress, filepath);
                attemptCount.incrementAndGet();
            } while (!log.equals("success") && attemptCount.get() < 5);
            String excelurl = "https://obs-top.obs.cn-north-1.myhuaweicloud.com/" + OBSAddress;

            rest.put("excelPath",excelurl);
            rest.put("code", 200);
            rest.put("message", "解析成功");
        } catch (IOException e) {
            e.printStackTrace();
            rest.put("excelPath","");
            rest.put("code", 500);
            rest.put("info", "");
            rest.put("message", "解析失败,"+e.toString());
        }
        return rest;
    }

    @Test
    public void chedkresultjx() throws IOException {
        List<CheckDTO> checkDTOS=new ArrayList<>();
        String filePath="D:\\wpzf\\440704.log";
        String tempath="D:\\wpzf";
        //解析日志文件 并解析存储到表
        try (BufferedReader br = new BufferedReader(new FileReader(filePath)))
        {
            String line;
            while ((line = br.readLine()) != null)
            {
                // 去掉首尾的方括号，并去掉部分之间的空格和方括号
                String trimmedInput = line.trim().substring(1, line.length() - 1);
                String[] parts = trimmedInput.split("\\] \\[");
                if(parts!=null)
                {
                    if (parts.length > 0&&parts.length==6)
                    {
                       if(parts[1].toString().equals("error"))
                       {
                           CheckDTO checkDTO=new CheckDTO();
                           checkDTO.setTime(parts[0].toString().replace("[",""));
                           checkDTO.setInfoLevel(parts[1].toString());
                           checkDTO.setTablename(parts[2].toString());
                           checkDTO.setId(parts[3].toString().replace("id:",""));
                           checkDTO.setMessage(parts[4].toString().replace("message:",""));
                           checkDTOS.add(checkDTO);
                       }
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        //checkDTOS 错误信息 与数据库对照
        if(checkDTOS.size()>0)
        {
            List<String> Colomnlist=new ArrayList<>();
            Colomnlist.clear();
            Colomnlist.add("表名");
            Colomnlist.add("级别");
            Colomnlist.add("定位字段");
            Colomnlist.add("定位值");
            Colomnlist.add("检查字段值");
            Colomnlist.add("错误描述");
            XSSFWorkbook workbook = new XSSFWorkbook();
            XSSFSheet sheet01 = workbook.createSheet("sheet1");
            XSSFRow row = sheet01.createRow(0);
            XSSFCellStyle style = workbook.createCellStyle();
            style.setAlignment(HorizontalAlignment.CENTER);
            int i = 0;
            for (String item : Colomnlist) {
                XSSFCell cell = row.createCell(i);
                String colName = (item);
                cell.setCellValue(colName);
                i++;
            }
            //图斑表错误信息
            for(int k=0;k<checkDTOS.size();k++)
            {
                CheckDTO checkDTO=checkDTOS.get(k);
                row = sheet01.createRow(k + 1);
                row.createCell(0).setCellValue(checkDTO.getTablename()+"");
                row.createCell(1).setCellValue(checkDTO.getInfoLevel()+"");
                row.createCell(2).setCellValue("BSM");
                row.createCell(3).setCellValue(checkDTO.getId());
                row.createCell(4).setCellValue("(xzqdm,bsm) = (440704,"+checkDTO.getId()+")");
                row.createCell(5).setCellValue(checkDTO.getMessage()+"");
            }
            String nowDate = new SimpleDateFormat("yyyyMMddHHMMss").format(new Date());
            FileOutputStream fileOut = new FileOutputStream(tempath + "/" + nowDate + ".xlsx");
            workbook.write(fileOut);
            fileOut.close();
        }
    }
}

